package com.ruoyi.web.controller.base.pc;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TinyUUIDGenerator;
import com.ruoyi.system.domain.po.*;
import com.ruoyi.system.domain.request.*;
import com.ruoyi.system.domain.valid.BasicParameter;
import com.ruoyi.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.apache.xmlbeans.impl.common.XBeanDebug.log;


/**
 * 人员告警Controller
 *
 * @author yingjie.liu
 * @date 2024-09-05
 */
@Slf4j
@RestController
@RequestMapping("/personnelAlarmPc")
public class PersonnelAlarmController extends BaseController {

    @Autowired
    private IPersonnelAlarmService personnelAlarmService;
    @Autowired
    private IPersonnelAlarmBodyAttrService personnelAlarmBodyAttrService;
    @Autowired
    private IPersonnelAlarmEventsAttrService personnelAlarmEventsAttrService;
    @Autowired
    private IRedisOperation redisOperation;
    @Autowired
    private IEmpInfoService empInfoService;
    @Autowired
    private ICameraService cameraService;
    @Autowired
    private IParameterService parameterService;
    @Autowired
    private IPersonnelAccountService personnelAccountService;

    @Autowired
    private AddUserService addUserService;
    @PostMapping("/createUser2AIE")
    @Transactional
    public AjaxResult createUser2Aie(@RequestParam("file") MultipartFile file
            , @RequestParam String userId
            , @RequestParam String userName
            , @RequestParam String card
            , @RequestParam String sex
            , @RequestParam String phone
            , @RequestParam String position
            , @RequestParam String empFromId
            , @RequestParam String workPlace
            , @RequestParam String jopId
            , @RequestParam String setEmpAttribute
    ) {

        EmpInfoReq req=new EmpInfoReq();
        req.setEmpId(userId);
        req.setEmpCard(card);
        req.setEmpImg(userId);
        req.setEmpName(userName);
        req.setEmpSex(sex);
        req.setEmpPhone(phone);
        req.setEmpPost(position);
        req.setEmpAttribute(setEmpAttribute);
        req.setEmpFromId(empFromId);
        req.setWorkPlace(workPlace);
        req.setJobId(jopId);

        PersonHelper helper =new PersonHelper();
        helper.addUserHelper(req,file,addUserService);

        return AjaxResult.error("成功");
    }

    @PostMapping("/get")
    @Transactional
    public AjaxResult receiveData(HttpServletRequest request) {

        String targetURL = BasicParameter.SERVER_FILE_ADDRESS; // 更改为你的服务器地址

        String json = request.getParameter("json");

        JsonData detail = new Gson().fromJson(json, JsonData.class);
        PersonnelAlarmController.log.info(json);
        PersonHelper helper = new PersonHelper();


        //人脸感知逻辑

        if (detail.getData() != null && detail.getData().getSnap_feat() != null) {
            Detail detail1 = detail.getData();
            String filePath = BasicParameter.IMG_STORAGE_ADDRESS + detail1.getSnap_id() + ".jpg"; // 更改为本地照片文件的路径
            //下载照片到本地 文件名 detail1.getSnap_id()+".jpg"
            helper.handleVideoUpload(request);
            Parameter parameter = parameterService.getById(1);

            //调用人脸检测接口获取抓拍图片人脸质量
            int quality = helper.getFaceCore(filePath);
            log.info("人脸检测质量:===============================================================>"+quality);
            //判断是否在人员库中
            if (detail1.getSimilarity() > 80 && quality > parameter.getQuality()) {
                PersonnelAccount personnelAccount = new PersonnelAccount();
                personnelAccount.setSnapId(detail1.getSnap_id());
                personnelAccount.setEmpId(detail1.getPerson_name());
                personnelAccount.setQuality(quality);
                personnelAccount.setCameraName(detail1.getCamera_name());
                personnelAccount.setLibId(detail1.getLib_id());
                personnelAccount.setDeviceId(detail1.getDevice_id());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime dateTime = LocalDateTime.parse(detail1.getTrigger(), formatter);
                personnelAccount.setSnapTime(dateTime);
                personnelAccountService.save(personnelAccount);
                //上传图片到服务器
                helper.uploadFile(targetURL, filePath);
                log.info("存入一条人员库感知信息");
                return AjaxResult.success();
            } else if (quality > parameter.getQuality()) {
                //根据照片对比库查看人员
                //String lib_ids = helper.callBackendService();
                String lib_ids = "4";
                NTopn nTopn = helper.sendFormData(lib_ids, filePath);
                if (nTopn == null) {
                    //如果陌生人库中还没有该人员 存入陌生人库中 并存入数据库中
                    String empId = TinyUUIDGenerator.generate();
                    EmpInfo empInfo = new EmpInfo();
                    empInfo.setEmpId(empId);
                    empInfo.setEmpName("Ta是谁?");
                    empInfo.setEmpImg(detail1.getSnap_id());
                    empInfoService.save(empInfo);
                    //添加人员库
                    helper.addArchives(lib_ids, filePath, detail1.getSnap_id(), empId);

                    PersonnelAccount personnelAccount = new PersonnelAccount();
                    personnelAccount.setSnapId(detail1.getSnap_id());
                    personnelAccount.setEmpId(empId);
                    personnelAccount.setQuality(quality);
                    personnelAccount.setCameraName(detail1.getCamera_name());
                    personnelAccount.setLibId(Integer.parseInt(lib_ids));
                    personnelAccount.setDeviceId(detail1.getDevice_id());
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime dateTime = LocalDateTime.parse(detail1.getTrigger(), formatter);
                    personnelAccount.setSnapTime(dateTime);
                    personnelAccountService.save(personnelAccount);
                    //上传图片到服务器
                    helper.uploadFile(targetURL, filePath);
                    log.info("存入一条陌生人库感知信息");
                    return AjaxResult.success();
                } else {
                    PersonnelAccount personnelAccount = new PersonnelAccount();
                    personnelAccount.setSnapId(detail1.getSnap_id());
                    personnelAccount.setEmpId(nTopn.getName());
                    personnelAccount.setQuality(quality);
                    personnelAccount.setCameraName(detail1.getCamera_name());
                    personnelAccount.setLibId(Integer.parseInt(lib_ids));
                    personnelAccount.setDeviceId(detail1.getDevice_id());
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime dateTime = LocalDateTime.parse(detail1.getTrigger(), formatter);
                    personnelAccount.setSnapTime(dateTime);
                    personnelAccountService.save(personnelAccount);
                    //上传图片到服务器
                    helper.uploadFile(targetURL, filePath);
                    log.info("存入一条陌生人库感知信息");
                    return AjaxResult.success();
                }
//                else {
//                    Parameter parameter = parameterService.getById(1);
//                    if (detail1.getQuality() < parameter.getQuality()){
//                        return AjaxResult.error("人脸图片质量过低");
//                    }else {
//
//                    }
//                }
            }
        }

        //告警业务
        if (detail.getData() == null || StringUtils.isEmpty(detail.getData().getEvents_type())) {
            return AjaxResult.error("非告警信息");
        } else {
            helper.handleVideoUpload(request);
            Detail detail1 = detail.getData();
            PersonnelAlarm personnelAlarm = new PersonnelAlarm();
            if (detail1.getEvents_type() == null) {
                return AjaxResult.error("非告警信息");
            } else {
//                String filePath = "/media/yasuo/9723f2a1-b4cc-4f10-a409-4280dd81b7d1/pic/"+detail1.getSnap_id()+".jpg"; // 更改为本地照片文件的路径
                String filePath = BasicParameter.IMG_STORAGE_ADDRESS + detail1.getSnap_id() + ".jpg"; // 更改为本地照片文件的路径
                String imgName = detail1.getSnap_id() + "jpg";
                //根据照片对比库查看人员
                String lib_ids = helper.callBackendService();
//                String lib_ids = "2";
                NTopn nTopn = helper.sendFormData(lib_ids, filePath);
                System.out.println("nTopn-------------:" + nTopn);

                if (nTopn != null) {
                    String name = nTopn.getName();
                    log.info("name:" + name + "===========================");
                    String eventsType = detail1.getEvents_type();
                    String key = name + eventsType;
                    boolean notOrYes = redisOperation.hasKey(key);
                    log.info("开始查看redis是否有值:" + redisOperation.getValue(key));
                    log.info("该报警事件是否出现:" + notOrYes + "=====================================");
                    if (redisOperation.hasKey(key)) {
                        log.error("5分钟内已出现该信息");
                        return AjaxResult.error("5分钟内已出现该信息");
                    }
                } else {
                    String key = "陌生人" + detail1.getEvents_type();
                    if (redisOperation.hasKey(key)) {
                        log.error("1分钟内已出现该信息");
                        return AjaxResult.error("1分钟内已出现该信息");
                    }
                }


                //上传图片到服务器
                helper.uploadFile(targetURL, filePath);

                if (detail1.getBody_attr() != null) {
                    PersonnelAlarmBodyAttr personnelAlarmBodyAttr = new PersonnelAlarmBodyAttr();
                    String bodyAttrId = TinyUUIDGenerator.generate();
                    personnelAlarmBodyAttr.setBodyAttrId(bodyAttrId);
                    BeanUtils.copyProperties(detail1.getBody_attr(), personnelAlarmBodyAttr);
                    personnelAlarmBodyAttrService.save(personnelAlarmBodyAttr);
                    personnelAlarm.setBody_attr_id(bodyAttrId);
                }
                if (detail1.getEvents_attr() != null) {
                    PersonnelAlarmEventsAttr personnelAlarmEventsAttr = new PersonnelAlarmEventsAttr();
                    String eventsAttrId = TinyUUIDGenerator.generate();
                    personnelAlarmEventsAttr.setEvents_attr_id(eventsAttrId);
                    BeanUtils.copyProperties(detail1.getEvents_attr(), personnelAlarmEventsAttr);
                    personnelAlarmEventsAttrService.save(personnelAlarmEventsAttr);
                    personnelAlarm.setEvents_attr_id(eventsAttrId);
                }
                BeanUtils.copyProperties(detail1, personnelAlarm);
                personnelAlarm.setMsg_id(detail.getMsg_id());
                if (nTopn != null) {

                    EmpInfo empInfo = empInfoService.getOne(new LambdaQueryWrapper<EmpInfo>().eq(EmpInfo::getEmpId,
                            nTopn.getName()));
                    personnelAlarm.setEmp_id(empInfo.getEmpId());
                    personnelAlarm.setPerson_addr(nTopn.getAddress());
                    personnelAlarm.setPerson_name(empInfo.getEmpName());
                    personnelAlarm.setPerson_age(nTopn.getAge());
                    personnelAlarm.setPerson_gender(nTopn.getGender());
                    personnelAlarm.setPerson_idcard(nTopn.getId());
                    personnelAlarm.setImg_id(nTopn.getImg_id());
                    personnelAlarm.setImg_path(nTopn.getImg_path());
                    personnelAlarm.setLib_id(nTopn.getLib_id());
                    personnelAlarm.setLib_name(nTopn.getLib_name());
                    personnelAlarm.setLib_type(nTopn.getLib_type());
                    personnelAlarm.setRanking(nTopn.getRanking());
                    personnelAlarm.setSimilarity(nTopn.getSimilarity());
                    personnelAlarm.setWander_deviceID(nTopn.getWanderdeviceId());
                    personnelAlarm.setWander_trigger(nTopn.getWandertrigger());

                    //存入redis 时间5分钟
                    String key = nTopn.getName() + personnelAlarm.getEvents_type();
                    redisOperation.setValue(key, personnelAlarm.getPerson_name(), 5L, TimeUnit.MINUTES);
                    log.info("key：" + key + "=====================================");
                    log.info("存入的reids：" + redisOperation.getValue(key) + "=====================================");
                } else {
                    String key = "陌生人" + personnelAlarm.getEvents_type();
                    redisOperation.setValue(key, "陌生人", 1L, TimeUnit.MINUTES);
                }
                String id = TinyUUIDGenerator.generate();
                personnelAlarm.setId(id);


                MpSendMsgReq sendMsgReq = new MpSendMsgReq();

                sendMsgReq.setId(personnelAlarm.getId());
                sendMsgReq.setTrigger(personnelAlarm.getTrigger());
                sendMsgReq.setAlarmArea("办公区");

                Map<String, String> eventsTypeMap = getStringStringMap();

                // 获取事件类型并设置到 sendMsgReq 对象中
                String eventType = personnelAlarm.getEvents_type();
                sendMsgReq.setEventsType(eventsTypeMap.getOrDefault(eventType, "未知事件"));

                if (!StringUtils.isBlank(personnelAlarm.getPerson_name())) {
                    sendMsgReq.setName(personnelAlarm.getPerson_name());
                } else {
                    sendMsgReq.setName("陌生人");
                }
                sendMsgReq.setState("未处理");

                //调用服务器接口推送公众号消息
                helper.sendMsg(sendMsgReq);


                personnelAlarmService.save(personnelAlarm);


            }
        }
        return AjaxResult.success();
    }

    private static Map<String, String> getStringStringMap() {
        Map<String, String> eventsTypeMap = new HashMap<>();
        eventsTypeMap.put("385", "打架斗殴");
        eventsTypeMap.put("387", "抽烟");
        eventsTypeMap.put("388", "人员睡岗");
        eventsTypeMap.put("389", "打电话");
        eventsTypeMap.put("390", "未佩戴安全帽");
        eventsTypeMap.put("391", "未穿工服");
        eventsTypeMap.put("392", "未穿反光衣");
        eventsTypeMap.put("395", "人员离岗");
        eventsTypeMap.put("396", "越界告警");
        eventsTypeMap.put("401", "未佩戴口罩");
        eventsTypeMap.put("403", "身体探出");
        eventsTypeMap.put("641", "明火");
        eventsTypeMap.put("642", "浓烟");
        eventsTypeMap.put("644", "占用消防通道");
        eventsTypeMap.put("646", "鼠患");
        return eventsTypeMap;
    }

}
